<template>
	<view class="area-b">
		<u-navbar title="群聊信息">
			<view slot="right" class="u-m-r-30" @tap="openSheet">
				<u-icon name="more-dot-fill" size="34"></u-icon>
			</view>
		</u-navbar>
		<view class="member-wrap u-m-t-20">
			<view class="item" v-for="(member,index) in someMember" :key="index" @tap="openMember(member)">
				<u-avatar :src="member.user&&(member.user.saveAvatar||member.user.avatarUrl)||member.avatar" size="100" mode="square"></u-avatar>
				<view class="name u-line-1 text-gray">
					{{(member.user&&(member.user.remarks||member.user.userName))||member.remarks||member.userName}}
				</view>
			</view>
			<navigator v-if="canInvite" :url="`/pages/group/member/add?id=${id}`" hover-class="none" class="item" key="add">
				<view class="oper">
					<u-icon name="plus" size="50" color="#AAAAAA"></u-icon>
				</view>
				<view class="name text-gray">
					添加
				</view>
			</navigator>
			<navigator :url="`/pages/group/member/remove?id=${id}`" hover-class="none" class="item" v-if="canManage" key="del">
				<view class="oper">
					<u-icon name="minus" size="50" color="#AAAAAA"></u-icon>
				</view>
				<view class="name text-gray">
					删除
				</view>
			</navigator>
			
			<navigator :url="`/pages/group/member/list?id=${id}`" hover-class="none" class="more text-grey">
				<view class="u-font-28">查看全部成员({{info.userCount||0}})</view>
			</navigator>
		</view>
		<view class="group u-border-bottom u-m-t-20" @tap="chooseAvatar">
			<text class="title u-font-28">群头像</text>
			<text class="text-gray u-font-28 main u-line-1"></text>
			<u-avatar :src="info.saveAvatar||info.avatar" size="100" mode="square"></u-avatar>
		</view>
		<view @tap="initJump('/pages/group/edit/name')" class="group u-border-bottom">
			<text class="title u-font-28">群名称</text>
			<text class="text-gray u-font-28 main">{{info.name||''}}</text>
			<text class="arrow iconfont icon-arrow-right text-gray"></text>
		</view>
		<view @tap="initJump('/pages/group/edit/brief')" class="group u-border-bottom">
			<text class="title u-font-28">群简介</text>
			<view class="text-gray u-font-28 main u-line-1">{{info.brief||''}}</view>
			<text class="arrow iconfont icon-arrow-right text-gray"></text>
		</view>
		<view class="group u-border-bottom" @tap="initJump(`/pages/group/notice/list?id=${id}`)">
			<text class="title u-font-28">群公告</text>
			<text class="text-gray u-font-28 main u-line-1">查看群公告列表</text>
			<text class="arrow iconfont icon-arrow-right text-gray"></text>
		</view>
		<view class="group u-border-bottom" @tap="initJump(`/pages/user/info?id=${info.userId}`)">
			<text class="title u-font-28">群主号</text>
			<text class="text-gray u-font-28 main u-line-1">{{info.userName||''}}</text>
			<text class="arrow iconfont icon-arrow-right text-gray"></text>
		</view>
		<!-- <view @tap="initJump('/pages/group/qrcode')" hover-class="none" class="group">
			<text class="title u-font-28">群二维码</text>
			<text class="text-gray u-font-30 main cuIcon-qrcode"></text>
			<text class="arrow iconfont icon-arrow-right text-gray"></text>
		</view> -->
		<navigator v-if="canManage" url="/pages/group/admin/admin" hover-class="none" class="group u-m-t-20">
			<text class="title u-font-28">群管理</text>
			<text class="arrow iconfont icon-arrow-right text-gray"></text>
		</navigator>
		<view class="group u-border-bottom u-m-t-20">
			<text class="title u-font-28">消息置顶</text>
			<u-switch :value="conversation.isTop" size="30" @change="topChange"></u-switch>
			<!-- <text class="arrow iconfont icon-arrow-right text-gray"></text> -->
		</view>
		<view class="group">
			<text class="title u-font-28">消息免打扰</text>
			<u-switch :value="conversation.isMute" size="30" @change="muteChange"></u-switch>
			<!-- <text class="arrow iconfont icon-arrow-right text-gray"></text> -->
		</view>
		
		<view class="group u-m-t-20 u-border-bottom" @tap="clearLog">
			<text class="title u-font-28">清除聊天记录</text>
			<text class="arrow iconfont icon-arrow-right text-gray"></text>
		</view>
		<view class="group u-m-t-20 u-border-bottom" @tap="searchLog">
			<text class="title u-font-28">查找聊天记录</text>
			<text class="arrow iconfont icon-arrow-right text-gray"></text>
		</view>
		<view class="group" @tap="complain">
			<text class="title u-font-28">举报投诉该群</text>
			<text class="arrow iconfont icon-arrow-right text-gray"></text>
		</view>
		<u-modal
			v-model="ask.show"
			title="" 
			showCancelButton
			:content="ask.content"
			@cancel="reject"
			@confirm="resolve"
		>
		</u-modal>
		<u-modal v-model="alert.show" :title="alert.title">
			<view class="u-p-30">
				<scroll-view class="u-text-center" scroll-y="true" :style="{maxHeight:'300rpx'}">
					<text class="u-font-28">{{alert.content}}</text>
				</scroll-view>
			</view>
		</u-modal>
		<u-action-sheet v-model="sheet.show" :list="sheet.options" @click="resolve"></u-action-sheet>
	</view>
</template>

<script>
	import {toast,delay,goback, jumpTo} from "@/utils/util.js"
	import * as fileUtil from "@/utils/file.js"
	import {state,event} from "./bus.js"
	import * as sessionAPI from "@/api/session.js"
	import {mapState,mapGetters,mapMutations,mapActions} from "vuex"
	import {fetchGroupInfo,fetchGroupMember,dismissGroup,quitGroup, getMyGroupAuth,editGroupAvatar} from "@/api/addr.js"
	import { TYPES as complainT } from "@/api/complain.js"
	import { ConversationType } from "@/entity/ConversationType.js"
	import DC from "@/DC/index.js"
	import { Member } from "@/entity/Member.js"
	import chat, { msgTypes } from "@/IM/index.js"
	export default {
		data() {
			return {
				id:'',
				ask:{
					show:false,
					content:''
				},
				sheet:{
					show:false,
					options:[]
				},
				alert:{
					show:false,
					content:'',
					title:''
				},
				bridge:null,
				lock:false,
				inited:false, 
				
				info:{},
				power:{},
				members:[]
			};
		},
		computed:{
			...mapGetters('user',['userInfo']),
			...mapState('chat',{
				conversation({conversationMap}){
					return conversationMap[this.id]
				}
			}),
			canInvite(){
				return this.canManage||this.info.isInvite
			},
			canAddFriend(){
				return this.canManage||this.info.isAddFriend
			},
			canManage(){
				return this.power.vest=='群主'||this.power.vest=='管理员'
			},
			someMember(){
				let num = 20
				if(this.canInvite){
					num--
				}
				if(this.canManage){
					num--
				}
				return this.members.slice(0,num)
			}
		},
		onLoad({id}) {
			this.id = id
			state.info = {}
			this.init()
			this.recurMembers()
			event.$on('reset_groupInfo',this.init)
			event.$on('reset_member',this.recurMembers)
		},
		onUnload() {
			event.$off('reset_groupInfo',this.init)
			event.$off('reset_member',this.recurMembers)
		},
		methods:{
			...mapActions('chat',['sendMessage','removeHistory','removeConversation','setConversation']),
			...mapActions('addr',['removeGroup']),
			...mapMutations('addr',['mixGroup']),
			resolve(e){
				this.bridge&&this.bridge.resolve&&this.bridge.resolve(e)
			},
			reject(e){
				this.bridge&&this.bridge.reject&&this.bridge.reject(e)
			},
			async muteChange(){
				if(this.lock){
					return
				}
				try{
					this.lock = true
					if(this.conversation.sid){
						await sessionAPI.setSilent({id:this.conversation.sid,status:this.conversation.isMute?0:1})
					}
					
					this.setConversation({
						...this.conversation,
						isMute:!this.conversation.isMute
					})
				}finally{
					this.lock = false
				}
			},
			async topChange(){
				if(this.lock){
					return
				}
				try{
					this.lock = true
					if(this.conversation.sid){
						await sessionAPI.setTop({id:this.conversation.sid,status:this.conversation.isTop?0:1})
					}
					
					this.setConversation({
						...this.conversation,
						isTop:!this.conversation.isTop
					})
				}finally{
					this.lock = false
				}
			},
			async init(){
				this.info = DC.groupDB.getGroup(this.id)
				this.info.fetchOrigin()
				
				
				this.power = await getMyGroupAuth(this.id)
				state.info = this.info
				state.power = this.power
				this.setConversation({
					...this.conversation,
					avatar:this.info.avatar,
					name:this.info.name
				})
				this.inited = true
			},
			async recurMembers(){
				const list = await fetchGroupMember({id:this.id,pageNo:1,pageSize:20})
				this.members = list.map((item)=>{
					const member = Member.origin2Ins(item)
					member.user = DC.userDB.getUser(member.userId)
					return member
				})
			},
			initJump(url){
				if(this.inited){
					jumpTo(url)
				}
			},
			openMember(member){
				if(member.vest=='群主'||member.vest=='管理员'||this.canAddFriend){
					return jumpTo(`/pages/user/info?id=${member.userId}`)
				}
			},
			async searchLog(){
				uni.navigateTo({
					url:`/pages/room/search?id=${this.id}&type=${ConversationType.Group}`
				})
			},
			async clearLog(){ 
				await new Promise((resolve,reject)=>{
					this.bridge = {
						resolve,
						reject
					}
					this.ask.show = true
					this.ask.content='确定要删除本群的聊天记录吗?'
				})
				const clearTime = await sessionAPI.clearHistory(this.id,'群')
				this.removeHistory(this.id)
				this.setConversation({
					id:this.conversation.id,
					clearTime
				})
				uni.$emit('clear_chat_history',{id:this.conversation.id,time:clearTime})
				await delay(500)
				toast('操作成功')
			},
			async complain(){ 
				jumpTo(`/pages/complain/index?btype=${complainT.group}&bid=${this.id}`)
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
			},
			async openSheet(){
				const index = await new Promise((resolve,reject)=>{
					this.bridge = {
						resolve,
						reject
					}
					this.sheet.show = true
					this.sheet.options = [{text:'退出群聊',fun:'quit'}]
					if(this.userInfo.userId==state.info.userId){
						this.sheet.options.push({text:'解散',fun:'dismiss'})
					}
				})
				const opt = this.sheet.options[index]
				console.log(opt)
				this[opt.fun]()
			},
			async quit(){ 
				await new Promise((resolve,reject)=>{
					this.bridge={
						resolve,
						reject
					}
					this.ask.show = true
					this.ask.content="确认退出当前群聊?"
				})
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				
				await quitGroup(state.info.id)
				this.removeConversation(state.info.id) 
				this.removeHistory(state.info.id) 
				this.removeGroup(state.info.id) 
				goback(2) 
			},
			async dismiss(){ 
				await new Promise((resolve,reject)=>{
					this.bridge={
						resolve,
						reject
					}
					this.ask.show = true
					this.ask.content="确认解散当前群聊吗?"
				})
				const msg = chat.createMessage({
					chatType:ConversationType.Group,
					groupId:this.id,
					content: `${this.userInfo.userName}解散了群聊`,
					msgType: msgTypes.INFORM,
					extras:{
						rich:`<span user="${this.userInfo.userId}">${this.userInfo.userName}</span>解散了群聊`
					}
				})
				await this.sendMessage({
					message: msg,
					id: this.id
				})
				uni.$emit('chat_receive',this.id,msg)
				await chat.send(msg)
				
				await dismissGroup(state.info.id)
				this.removeConversation(state.info.id) 
				this.removeHistory(state.info.id) 
				this.removeGroup(state.info.id) 
				goback(2) 
			},
			openNotice(){
				if(!this.inited){
					return
				}
				
				if(this.canManage){
					jumpTo(`/pages/group/edit/notice`)
				}else{
					this.alert.show = true
					this.alert.content = this.info.notice
					this.alert.title = '群公告'
				}
			},
			async chooseAvatar(){
				if(!this.inited){
					return
				}
				if(this.power.vest!='群主'){
					if(this.info.avatar){
						uni.previewImage({
							current:this.info.saveAvatar||this.info.avatar,
							urls:[this.info.saveAvatar||this.info.avatar]
						})
					}
					return
				}
				if(this.chooseAvatar.lock){
					return
				}
				uni.$off("uAvatarCropper")
				let file = await new Promise((resolve,reject)=>{
					uni.$once("uAvatarCropper",resolve)
					jumpTo("/uview-ui/components/u-avatar-cropper/u-avatar-cropper?destWidth=600&rectWidth=200&fileType=png")
				})
				try{
					this.chooseAvatar.lock = true
					const avatarUrl = await fileUtil.uploadFile({pre:'head/',file})
					
					await editGroupAvatar({
						id:this.info.id,
						avatar:avatarUrl
					})
					this.setConversation({
						...this.conversation,
						avatar:avatarUrl
					})
					state.info.avatar = avatarUrl
					this.mixGroup({...state.info})
				}catch(e){
					console.error(e)
					toast(e.message||"上传失败,稍后尝试")
				}finally{
					this.chooseAvatar.lock = false
				}
			},
			
		}
	}
</script>
<style>
	page{
		background-color: #F5F5F5;
	}
</style>
<style lang="scss" scoped>
	.member-wrap{
		display: grid;
		padding: 30rpx 30rpx 20rpx;
		background-color: #FFFFFF;
		grid-template-columns: repeat(5,1fr);
		grid-gap: 30rpx;
		.item{
			display: flex;
			flex-direction: column;
			align-items: center;
		}
		.name{
			max-width: 100rpx;
			font-size: 24rpx;
			margin-top: 10rpx;
		}
		.oper{
			width: 100rpx;
			height: 100rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			border: 2rpx dashed #AAAAAA;
			border-radius: 10rpx;
		}
		.more{
			grid-column-start: 1;
			grid-column-end: 6;
			background-color: #F5F5F5;
			display: flex;
			justify-content: center;
			align-items: center;
			padding: 10rpx;
			border-radius: 10rpx;
		}
	}
	.group{
		background-color: #FFFFFF;
		display: flex;
		align-items: center;
		padding: 20rpx 30rpx;
		.title{
			margin-right: 20rpx;
			flex: 1;
		}
		.main{
			max-width: 480rpx;
		}
		.arrow{
			margin-left: 10rpx;
		}
	}
</style>
